const gulp = require('gulp');
const sequence = require('gulp-sequence');
const shell = require('gulp-shell');

gulp.task('compile-ts', shell.task('tsc -m esnext -p ./tsconfig-ali-app.json'));

gulp.task('watch-ts', shell.task('tsc -m esnext -p ./tsconfig-ali-app.json -w'));

gulp.task('copy-files', () => {
	const copy = require('gulp-copy');
	const dist = './dist/';
	return gulp.src([
		'./src-ali-app/**/*.json',
		'./src-ali-app/app.js',
		'./src-ali-app/app.acss',
		'./src-ali-app/app.json',
		'./src-ali-app/pages/**/*',
		'./src-ali-app/images/**/*',
		'./src-ali-app/css/**/*'
	]).pipe(copy(dist, {
		prefix: 1
	}));
});

gulp.task('watch-files', () => {
	const copy = require('gulp-copy');
	const dist = './dist/';
	return gulp.watch([
		'./src-ali-app/*.js',
		'./src-ali-app/*.acss',
		'./src-ali-app/pages/*/*.json',
		'./src-ali-app/**/*.acss',
		'./src-ali-app/**/*.axml',
		'./src-ali-app/images/**/*'
	], (file) => {
		// file.type added renamed deleted changed
		gulp.src(file.path)
			.pipe(copy(dist, {
				prefix: 1
			}));
	});
});

gulp.task('watch-file-app-debug', () => {
	const source = './src-ali-app/app-debug.json';
	const dist = './dist/';
	const rename = require('gulp-rename');
	return gulp.watch(source, () => {
		// file.type added renamed deleted changed
		return gulp.src(source)
			.pipe(rename('app.json'))
			.pipe(gulp.dest(dist));
	});
});

gulp.task('pack', sequence(
	'compile-ts',
	'copy-files'
));

gulp.task('copy-app-debug', () => {
	const dist = './dist/';
	const rename = require('gulp-rename');
	return gulp.src('./src-ali-app/app-debug.json')
		.pipe(rename('app.json'))
		.pipe(gulp.dest(dist));
});

gulp.task('dev', shell.task(`feidao-dev -s ${process.cwd()}/service/dist/`));

gulp.task('service-watch', shell.task(`tsc -w -p ./service/tsconfig.json`));

gulp.task('weapp', sequence('copy-files', 'copy-app-debug', ['watch-files', 'watch-file-app-debug', 'watch-ts', 'dev', 'service-watch']));

gulp.task('ali-app-add', () => {
	const fs = require('fs').promises;
	const repl = require('repl');
	return repl.start({
		prompt: '\nPlease type 1 pagename each time. and stop with [ctrl+d]\n>', async eval(cmd, context, _filename, callback) {
			const filename = cmd.trim();
			if (cmd) {
				try {
					// js
					const wxdir = `./src-ali-app/pages/${filename}`;
					await fs.mkdir(wxdir);
					const jsfile = `./src-ali-app/pages/${filename}/${filename}.js`;
					const jsfile_content = `import '../../${filename}/p';
`;
					await fs.writeFile(jsfile, jsfile_content, 'utf8');
					// json
					const jsonfile = `./src-ali-app/pages/${filename}/${filename}.json`;
					const jsonfile_content = `{}`;
					await fs.writeFile(jsonfile, jsonfile_content, 'utf8');
					// axml
					const axmlfile = `./src-ali-app/pages/${filename}/${filename}.axml`;
					const axmlfile_content = `\n`;
					await fs.writeFile(axmlfile, axmlfile_content, 'utf8');
					// acss
					const acssfile = `./src-ali-app/pages/${filename}/${filename}.acss`;
					const acssfile_content = `\n`;
					await fs.writeFile(acssfile, acssfile_content, 'utf8');
					// ts
					const tsdir = `./src-ali-app/${filename}`;
					await fs.mkdir(tsdir);
					// s.ts
					const sfile = `./src-ali-app/${filename}/s.ts`;
					const sfile_content = `export default {\n\t'fd-events-init': 'a001'\n};\n`;
					await fs.writeFile(sfile, sfile_content, 'utf8');
					// a001.ts
					const afile = `./src-ali-app/${filename}/a001.ts`;
					const afile_content = `import { IFeidaoAiWeappPage } from '@feidao/web/interfaces';

export default async function a001(fd: IFeidaoAiWeappPage, ...args: any[]) {
	// todo
}
`;
					await fs.writeFile(afile, afile_content, 'utf8');
					// p.ts
					const pfile = `./src-ali-app/${filename}/p.ts`;
					const pfile_content = `import init from '@feidao/web/framework/aliapp/d/page';

import s from './s';

import a001 from './a001';

export default function main() {
	const actions = {
		a001
	};

	return init(s, actions);
}
`;
					await fs.writeFile(pfile, pfile_content, 'utf8');
				} catch (error) {
					console.error(error);
					callback();
				}
			}
			callback();
		}
	});
});

gulp.task('ali-app-fix', async () => {
	const globby = require('globby');
	const path = require('path');
	const fs = require('fs').promises;
	try {
		const paths = await globby('./src-ali-app/*/p.ts');
		const filenames = paths.map((filepath) => {
			return filepath.match(/.*\/(.*)\/p.ts/)[1];
		});
		const app = require('./src-ali-app/app.json');
		app.pages = filenames.map((filename) => {
			return `pages/${filename}/${filename}`;
		});
		await fs.writeFile('./src-ali-app/app.json', JSON.stringify(app, null, '\t'), 'utf8');
		await filenames.map(async (filename) => {
			const jsfile = `./src-ali-app/pages/${filename}/${filename}.js`;
			try {
				await fs.access(jsfile);
			} catch (error) {
				console.log(`generage file ${jsfile}`);
				const file = `import init from '../../${filename}/p';
Page(init());
`;
				await fs.writeFile(jsfile, file, 'utf8');
			}
		});
	} catch (error) {
		console.error(`There is no such dir src-ali-app`);
	}
});
